import { Injectable } from '@nestjs/common';
import { VoteLogModelService } from 'src/models/vote-log-model/vote-log-model.service';
import { VoteModelService } from 'src/models/vote-model/vote-model.service';
import { VoteOptionModelService } from 'src/models/vote-option-model/vote-option-model.service';
import { errorReturn, successReturn } from 'src/utils';
var moment = require('moment');

@Injectable()
export class VoteService {
    constructor(private voteModelService:VoteModelService, private voteOptionModelService:VoteOptionModelService, private voteLogModelService:VoteLogModelService) {

    }

    async getVoteById(id:number = 0) {
        let row = await this.voteModelService.findOne({id : id})
        let options = await this.voteModelService.querySql(`select * from vote_options where vote_id = ${id}`)

        let myVote =  await this.voteLogModelService.findOne({user_id : 1, vote_id : id}) 

        return {
            ...row,
            options,
            voted : myVote
        }
    }

    async getPageById(id:number = 0, pageSize:number = 15) {
        let sql = 'select * from vote'
        if(id > 0) {
            sql += ` where id < ${id}`
        }
        sql += ` order by id desc limit ${pageSize}`

        let rows = await this.voteModelService.querySql<any[]>(sql)
        
        return rows

        // let voteIds = rows.map(row => row.id).join(',')

        // let options = await this.voteOptionModelService.querySql<any[]>(`select * from vote_options where vote_id in (${voteIds})`)

        // rows.forEach(row => {
        //     row.options = []
        //     let voteId = row.id
        //     for(let i = 0; i < options.length;) {
        //         let option = options[i]
        //         if(voteId == option.vote_id) {
        //             row.options.push(...options.splice(i, 1))
        //         }else {
        //             i ++
        //         }
        //     }
        // })

        // return rows
    }

    async vote(optionId:number) {
        let option = await this.voteOptionModelService.findOne({id : optionId})
        if(!option) return errorReturn('投票失败1')

        let vote = await this.voteModelService.findOne({id : option.vote_id})
        if(!vote) return errorReturn('投票失败2')

        let row = await this.voteLogModelService.findOne({user_id : 1, vote_id : option.vote_id})
        if(row) return errorReturn('您已经投过票')

        let time = moment().unix()

        if(vote.expire_in <= time) return errorReturn('投票已结束')


        this.voteModelService.querySql(`update vote set total_score = total_score + 1 where id = ${option.vote_id}`)
        this.voteOptionModelService.querySql(`update vote_options set score = score + 1 where id = ${optionId}`)
        this.voteLogModelService.insert({user_id : 1, vote_id : option.vote_id, vote_option_id : optionId, create_time : time})

        return successReturn('投票成功')
    }
}
